<script setup>
import { computed, onMounted, reactive, ref, toRefs } from 'vue';
import { useRoute } from 'vue-router';
import { ElInput, ElMessage, ElMessageBox, ElTable, ElTableColumn, ElTag, ElTree } from 'element-plus';
import {
  delSystemUser,
  getSystemUserPage,
  postSystemUser,
  putSystemUser,
  putSystemUserRestPass,
} from '@/apis/api-system';
import { OPERATION_TYPE } from '@/common/common-const';
import PaginationIndex from '@/components/PaginationIndex.vue';
import ReleasePromptMessage from '@/components/ReleasePromptMessage.vue';
import SvgIconIndex from '@/components/SvgIconIndex.vue';
import { useSystemStore, useUserStore } from '@/stores';
import { clearToken } from '@/utils/auth';
import ReleaseUserOperation from './ReleaseUserOperation.vue';

const props = defineProps({
  name: {
    type: String,
  },
});
const { name } = toRefs(props);

const systemStore = useSystemStore();
const userStore = useUserStore();
const route = useRoute();

const defaultProps = {
  id: 'id',
  children: 'children',
  label: 'name',
};
const treeData = ref([]);
const tableLoading = ref(false);
const userShow = ref(false);
const userType = ref('');
const userData = ref({});
const tableData = ref([]);

const titleName = computed(() => name.value);
const total = ref(0);
const checkedTreeItem = ref({});
const treeRef = ref(null);

const selectParams = reactive({
  pageNumber: 1,
  pageSize: 10,
  deptId: '',
  username: '',
  nickname: '',
});

const messageInfo = reactive({
  messageBoxShow: false,
  messageText: '',
  messageBoxType: '',
});

const handleUserShowEmit = () => {
  userShow.value = false;
  userType.value = '';
  userData.value = {};
};

// 分页
const handleCurrentChange = (val) => {
  selectParams.pageNumber = val;
  getSystemUserPageApi(selectParams);
};

// 操作
const handleOperation = (type, item) => {
  userType.value = type;

  if (type == OPERATION_TYPE.DELETE) {
    messageInfo.infoBoxValue = item;
    messageInfo.messageBoxType = '删除';
    messageInfo.messageBoxShow = true;

    if (messageInfo.infoBoxValue.id == userStore.userInfo.id) {
      messageInfo.messageText = '系统系别您要删除自己的账号，删除后不可恢复';
    } else {
      messageInfo.messageText = '该数据删除后不可恢复，确定要删除吗？';
    }
  }

  if (type == OPERATION_TYPE.EDIT) {
    userShow.value = true;
    userData.value = item;
  }

  if (type == OPERATION_TYPE.ADD) {
    userShow.value = true;
  }

  if (type == OPERATION_TYPE.REST) {
    ElMessageBox.confirm('确定要重置密码吗？', '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      customClass: 'message-reset',
    })
      .then(() => {
        resetPasswordAPI(item.id);
      })
      .catch((err) => {
        return err;
      });
  }
};

const handleMessageBox = (val) => {
  messageInfo.messageBoxShow = false;
  messageInfo.messageText = '';

  if (val) {
    //  删除接口

    deleteSystemUserApi(messageInfo.infoBoxValue.id);
  }

  messageInfo.messageBoxType = '';
};

const handleNodeClick = (item) => {
  if (item.id === selectParams?.deptId) {
    treeRef.value.setCurrentKey(null);

    checkedTreeItem.value = {};
    selectParams.deptId = '';
  } else {
    checkedTreeItem.value = item;
    selectParams.deptId = item.id;
  }

  handleReset();
};

onMounted(() => {
  treeData.value = systemStore.systemDept;

  getSystemUserPageApi(selectParams);
});

const handleReset = () => {
  selectParams.pageNumber = 1;
  selectParams.username = '';
  selectParams.nickname = '';

  getSystemUserPageApi(selectParams);
};

const handleSelect = () => {
  getSystemUserPageApi(selectParams);
};

// 数据
const handleUserParamEmit = (value, type) => {
  if (type == 'ADD') {
    postSystemUserApi(value);
  } else {
    putSystemUserApi(value);
  }
};

/*
 *@description: 获取用户列表
 *@author:chen_fei
 *@Date: 2024-06-17 10:11:25
 */
const getSystemUserPageApi = async (value) => {
  tableLoading.value = true;

  const [err, data] = await getSystemUserPage(value);

  if (!err) {
    tableData.value = data.data.records;
    total.value = data.data.total;
  }

  tableLoading.value = false;
};

/*
 *@description: 新增用户
 *@author:chen_fei
 *@Date: 2024-06-17 10:13:21
 */
const postSystemUserApi = async (value) => {
  const [err] = await postSystemUser(value);

  if (!err) {
    ElMessage.success('新增成功');
    handleUserShowEmit();
  }

  getSystemUserPageApi(selectParams);
};

/*
 *@description: 编辑用户
 *@author:chen_fei
 *@Date: 2024-06-17 10:13:33
 */
const putSystemUserApi = async (value) => {
  const [err] = await putSystemUser(value, value.id);

  if (!err) {
    ElMessage.success('编辑成功');
    handleUserShowEmit();

    if (value.id == userStore.userInfo.id) {
      userStore.SELECT_LOGIN_CURRENT();
    }
  }

  getSystemUserPageApi(selectParams);
};

/*
 *@description: 删除用户
 *@author:chen_fei
 *@Date: 2024-06-17 10:13:50
 */
const deleteSystemUserApi = async (id) => {
  const [err] = await delSystemUser(id);

  if (!err) {
    ElMessage.success('删除成功!');

    if (id == userStore.userInfo.id) {
      ElMessage({
        message: `系统识别您删除了自己的账号，请前往登录页面，重新登录！`,
        type: 'warning',
      });
      setTimeout(() => {
        clearToken();

        if (route.path !== '/login') {
          location.reload();
        }
      }, 1000);
    }
  }

  messageInfo.infoBoxValue = '';
  getSystemUserPageApi(selectParams);
};

/*
 *@description: 重置密码
 *@author:chen_fei
 *@Date: 2024-06-17 14:48:35
 */
const resetPasswordAPI = async (ids) => {
  const [err] = await putSystemUserRestPass(ids);

  if (!err) {
    ElMessage.success('重置成功');

    if (ids == userStore.userInfo.id) {
      ElMessage({
        message: `系统识别您重置了自己的密码，请前往登录页面，重新登录！`,
        type: 'warning',
      });
      setTimeout(() => {
        clearToken();

        if (route.path !== '/login') {
          location.reload();
        }
      }, 1000);
    }
  } else {
    ElMessage.error('重置失败');
  }
};
</script>
<template>
  <div class="root h-100% w-100% rounded-5px">
    <div class="flex-x-center">
      <div class="left_box">
        <h3>组织架构</h3>
        <div class="tree_box">
          <ElTree
            ref="treeRef"
            node-key="id"
            class="filter-tree"
            default-expand-all
            :data="treeData"
            :props="defaultProps"
            :highlight-current="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="right_box">
        <h3>{{ titleName }}</h3>

        <div class="mb-20px mt-20px flex-x-between">
          <div class="select_top mt-20px flex-center">
            <div class="select_u flex-center">
              <div class="flex-center">
                <span>用户名</span>
                <ElInput v-model="selectParams.username" placeholder="请输入(精确查询)" />
              </div>
              <div class="flex-center">
                <span>姓名</span>
                <ElInput v-model="selectParams.nickname" placeholder="请输入(模糊查询)" />
              </div>
            </div>
          </div>
          <div class="mt-20px flex-center">
            <div class="select_btn mr-20px flex-center">
              <div @click="handleReset()">重置</div>
              <div @click="handleSelect()">查询</div>
            </div>
            <div class="btn-add flex-center cursor-pointer" @click="handleOperation('ADD')">
              <SvgIconIndex icon-class="add" size="20px" class="cursor-pointer" />新建
            </div>
          </div>
        </div>
        <div>
          <ElTable
            v-loading="tableLoading"
            :data="tableData"
            style="width: 100%"
            border
            row-key="id"
            :header-cell-style="{
              color: '#333333',
              background: 'rgba(97, 186, 55, 0.06)',
            }"
          >
            <ElTableColumn type="index" label="序号" align="center" width="65" />
            <ElTableColumn prop="username" label="用户名" align="center" show-overflow-tooltip />
            <ElTableColumn prop="nickname" label="姓名" align="center" show-overflow-tooltip />
            <ElTableColumn prop="gender" label="性别" align="center" show-overflow-tooltip>
              <template #default="scope">
                <div>
                  <div v-if="scope.row.gender">
                    {{ scope.row.gender == 1 ? '女' : '男' }}
                  </div>
                  <p v-if="!scope.row.gender">--</p>
                </div>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="mobile" label="电话" align="center" show-overflow-tooltip />
            <ElTableColumn prop="deptName" label="部门" align="center" show-overflow-tooltip />
            <ElTableColumn prop="roleList" label="角色" align="center" show-overflow-tooltip>
              <template #default="scope">
                <div
                  :title="
                    scope.row.roleList
                      .map((item) => {
                        return item.title;
                      })
                      .join('、')
                  "
                >
                  <div v-if="scope.row.roleList.length">
                    <ElTag v-for="item in scope.row.roleList" :key="item.id" size="large" type="warning">{{
                      item?.title
                    }}</ElTag>
                  </div>
                  <p v-if="!scope.row.roleList.length">--</p>
                </div>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="createdDate" label="创建时间" align="center" show-overflow-tooltip />
            <ElTableColumn label="操作" align="center" width="240">
              <template #default="scope">
                <div class="flex items-center justify-around">
                  <div
                    class="edit_btn h-35px w-75px flex-center cursor-pointer"
                    @click="handleOperation('EDIT', scope.row)"
                  >
                    编辑
                  </div>
                  <div
                    class="rest_btn h-35px w-85px flex-center cursor-pointer"
                    @click="handleOperation('REST', scope.row)"
                  >
                    重置密码
                  </div>
                  <div
                    class="del_btn h-35px w-75px flex-center cursor-pointer"
                    @click="handleOperation('DELETE', scope.row)"
                  >
                    删除
                  </div>
                </div>
              </template>
            </ElTableColumn>
          </ElTable>
        </div>
        <PaginationIndex
          :page-number="selectParams.pageNumber"
          :page-size="selectParams.pageSize"
          :total="total"
          @handle-current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 提示 -->
  <ReleasePromptMessage
    v-if="messageInfo.messageBoxShow"
    :message-box-show="messageInfo.messageBoxShow"
    :message-text="messageInfo.messageText"
    :message-box-type="messageInfo.messageBoxType"
    @handle-message-box="handleMessageBox"
  />

  <ReleaseUserOperation
    v-if="userShow"
    :user-data="userData"
    :user-type="userType"
    :user-show="userShow"
    :checked-tree-item="checkedTreeItem"
    @handle-user-param-emit="handleUserParamEmit"
    @handle-user-show-emit="handleUserShowEmit"
  />
</template>

<style scoped lang="scss">
.root {
  padding: 1.5rem;
  font-size: $base-system-font-size-base;
  background-color: $base-background-white;

  .left_box {
    width: 300px;
    height: 100%;

    h3::before {
      content: '|';
      width: 4px;
      height: 30px;
      margin-right: 5px;
      color: $base-color-green;
      font-size: 18px;
      background-color: $base-color-green;
    }

    .tree_box {
      width: 100%;
      max-height: 837px;
      margin-top: 30px;
      padding-right: 20px;
      overflow: auto;

      &::-webkit-scrollbar {
        display: none;
        width: 0 !important;
      }

      :deep(.el-tree-node__content) {
        height: 40px;
        padding-right: 9px;
        font-size: 18px;
      }

      :deep(.el-tree-node:focus > .el-tree-node__content) {
        background-color: #fff;
      }

      :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
        background-color: #f0fcf2;
      }
    }
  }
  .right_box {
    width: calc(100% - 300px);
    .select_top {
      .select_u {
        display: flex;
        white-space: nowrap;
        div {
          display: flex;
          align-items: center;
          margin-right: 20px;

          span {
            display: inline-block;
            margin-right: 12px;
          }
        }
      }

      :deep(.el-input .el-input__wrapper) {
        width: 240px;
        height: 40px;
      }
      :deep(.el-select__wrapper) {
        width: 240px;
        height: 40px;
      }
    }
    .select_btn {
      display: flex;
      div {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100px;
        height: 40px;
        font-size: 16px;
        border-radius: 4px;
        cursor: pointer;

        &:first-child {
          margin-right: 16px;
          color: #999999;
          background: rgba(171, 171, 171, 0.2);
        }

        &:nth-child(2) {
          color: $base-button-color-green;
          background: $base-button-background-green;
        }
      }
    }

    .btn-add {
      width: 100px;
      height: 40px;
      color: $base-button-color-white;
      background-color: $base-button-color-green;
      border-radius: 5px;
    }
    .edit_btn,
    .rest_btn,
    .del_btn {
      font-size: $base-system-font-size-base;
      border-radius: 5px;
    }
    .edit_btn {
      color: $base-button-color-blue;
      background-color: $base-button-background-blue;
    }
    .rest_btn {
      color: $base-button-color-green;
      background-color: $base-button-background-green;
    }
    .del_btn {
      color: $base-button-color-red;
      background-color: $base-button-background-red;
    }
  }
}
</style>
